﻿using Dapper;
using Gx.Common.Core;
using Gx.Model.Entity;
using Gx.Model.ViewModel;
using System.Collections.Generic;
using System.Linq;
namespace Gx.Dal.Manage
{
    public class LKWareHouseDal:BaseDal<LKWareHouse>
    {
    
        /// <summary>
        /// 名称是否存在
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool AnyName(string name)
        {
            using (var conn = new DbContext())
            {
                var total = conn.Connection.QueryFirst<int>("SELECT COUNT(1) FROM LK_WareHouse WHERE IsDeleted=0 AND WareHouseName=@name", new { name });
                return total > 0;
            }
        }
        
        /// <summary>
        /// 获取最大编号
        /// </summary>
        /// <returns></returns>
        public string GetMaxLKWareHouseCode()
        {
            using (var conn = new DbContext())
            {
                return conn.Connection.QueryFirst<string>("SELECT MAX(LKWareHouseCode) FROM LK_WareHouse");
            }
        }

        public List<LKWareHouse> GetLKWareHouses()
        {
            using (var conn = new DbContext())
            {
                return conn.Connection.Query<LKWareHouse>(@"SELECT h.*,c.CompanyName FROM dbo.LK_WareHouse h
LEFT JOIN dbo.LK_Company c ON h.CompanyId=c.Id AND c.IsDeleted=0
WHERE h.IsDeleted=0").ToList();
            }
        }

        public List<int> GetWareHouseByParentId(int houseId) 
        {
            using (var conn = new DbContext())
            {
                string housesql = @"WITH RecursiveHouse AS (
    SELECT Id, ParentId
    FROM LK_WareHouse WITH(NOLOCK)
    WHERE ParentId = @houseId  -- 这里的@ParentID是要查询子节点的起始节点ID
    UNION ALL
    SELECT o.Id, o.ParentId
    FROM LK_WareHouse AS o WITH(NOLOCK)
    INNER JOIN RecursiveHouse AS r ON o.ParentId = r.Id
)
SELECT Id FROM RecursiveHouse;";

                var hids = conn.Connection.Query<int>(housesql, new { houseId }).ToList();
                return hids;
            }
        }

        //public PagedList<LKWareHouse> GetLKWareHouseList(LKWareHouseInput input)
        //{
        //    string sql = "SELECT * FROM LK_WareHouse WHERE IsDeleted=0 @WHERE";
        //    List<string> conditions = new List<string>();

        //    string condition = string.Empty;
        //    if (conditions.Any())
        //    {
        //        condition = $" AND {string.Join(" AND ", conditions)}";
        //    }
        //    sql = !string.IsNullOrWhiteSpace(condition) ? sql.Replace("@WHERE", condition) : sql.Replace("@WHERE", "");

        //    using (var conn = new DbContext())
        //    {
        //        return conn.Connection.GetPagedList<LKWareHouse>(sql, "CreateTime Desc", input);
        //    }
        //}
    }
}

